package com.selftaught.domain.hcpatientinfo;

import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.StringReader;
import java.util.List;

/**
 * XmlResponseParser
 *
 * @author huya
 * @date 2025-10-23
 */
@Component
public class XmlResponseParser {

    private static final Logger logger = LoggerFactory.getLogger(XmlResponseParser.class);

    /**
     * 将 XML 字符串解析为 HcpatientinfoResponse 对象
     *
     * @param xmlResponse XML 响应字符串
     * @return 解析后的对象
     */
    public HcpatientinfoResponse parseResponse(String xmlResponse) {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(HcpatientinfoResponse.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            StringReader reader = new StringReader(xmlResponse);
            HcpatientinfoResponse response = (HcpatientinfoResponse) unmarshaller.unmarshal(reader);
            logger.info("解析XML响应成功");
            return response;
        } catch (JAXBException e) {
            logger.error("解析XML响应失败: {}", e.getMessage(), e);
            throw new RuntimeException("解析XML响应失败: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        XmlResponseParser parser = new XmlResponseParser();
        String xmlResponse = "<root xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><header><NHIPlog><status>AA</status></NHIPlog><msgCode>900</msgCode><msgId>048c1a58-c274-44f1-85e4-7e4c3bfc6f49</msgId><type>900</type><createTime>20251023133604</createTime></header><body><items><item><patName>张三</patName><patSex>F</patSex><patAge>51</patAge><patBirth>1973/10/28 0:00:00</patBirth><patAddress>江苏省南京市江宁区丽泽路xx号</patAddress><patMobile>12312312312</patMobile><patIdType>1</patIdType><patIdNo>123123123123123123</patIdNo><patCardType>1</patCardType><patCardNo>0012312312</patCardNo><patientId>1231231231231231</patientId><patType>1</patType><totalAmt>200</totalAmt></item></items></body></root>";
        HcpatientinfoResponse hcpatientinfoResponse = parser.parseResponse(xmlResponse);
        if (hcpatientinfoResponse != null) {
            HcpatientinfoResponse.ResponseBody body = hcpatientinfoResponse.getBody();
            if (body != null) {
                HcpatientinfoResponse.ResponseBody.Items items = body.getItems();
                if (items != null) {
                    List<HcpatientinfoResponse.PatientItem> item = items.getItem();
                    if (!item.isEmpty()) {
                        HcpatientinfoResponse.PatientItem patientInfoItem = item.get(0);
                        if (patientInfoItem != null) {
                            System.out.println(patientInfoItem);
                        }
                    }
                }
            }
        }
    }
}
